package com.aia.prm.web.ria.app.ui.plan;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Arrays;
import java.util.List;

import org.apache.log4j.Logger;

import com.aia.prm.domain.VOPlan;
import com.aia.prm.web.ria.app.ui.ConfirmDialog;
import com.vaadin.data.Item;
import com.vaadin.data.util.BeanItem;
import com.vaadin.data.validator.IntegerValidator;
import com.vaadin.terminal.ThemeResource;
import com.vaadin.ui.Button;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.Button.ClickListener;
import com.vaadin.ui.ComboBox;
import com.vaadin.ui.Component;
import com.vaadin.ui.DefaultFieldFactory;
import com.vaadin.ui.Field;
import com.vaadin.ui.Form;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.TextField;

@SuppressWarnings("serial")
public class PlanForm extends Form implements ClickListener {
	private static final Logger logger = Logger.getLogger(PlanForm.class);
	private Button save = new Button("保存", (ClickListener) this);
	private Button cancel = new Button("取消", (ClickListener) this);
	private Button edit = new Button("编辑", (ClickListener) this);
	private Button delete = new Button("删除", (ClickListener) this);
	private boolean newContactMode = false;
	private VOPlan newVOPlan = null;
	private final ComboBox types = new ComboBox("模板");
	PlanView view = null;

	public PlanForm(PlanView aview) {
		setIcons();
		view = aview;
		getLayout().setMargin(true);
		// setCaption("");
		setSizeFull();
		setWriteThrough(false);
		HorizontalLayout footer = new HorizontalLayout();
		footer.setSpacing(true);
		footer.addComponent(save);
		footer.addComponent(cancel);
		footer.addComponent(edit);
		footer.addComponent(delete);
		footer.setVisible(false);
		setFooter(footer);
		setFormFieldFactory(new DefaultFieldFactory() {
			public Field createField(Item item, Object propertyId, Component uiContext) {
				if ("PL_TYPE".equals(propertyId)) {
					return types;
				}

				if ("PL_DESC".equals(propertyId)) {
					com.vaadin.ui.TextArea editor = new com.vaadin.ui.TextArea(null, "");
					editor.setRows(8);
					editor.setColumns(20);

					if (PlanContainer.FIELD_NAME_MAP.containsKey(propertyId)) {
						editor.setCaption(PlanContainer.FIELD_NAME_MAP.get(propertyId));
					}

					editor.setNullRepresentation("");

					return editor;
				}
				Field field = super.createField(item, propertyId, uiContext);
				if (field instanceof TextField) {
					((TextField) field).setNullRepresentation("");
					((TextField) field).setNullSettingAllowed(true);
				}
				if (PlanContainer.FIELD_NAME_MAP.containsKey(propertyId)) {
					field.setCaption(PlanContainer.FIELD_NAME_MAP.get(propertyId));
				}
				if ("PL_ORDER".equals(propertyId) || "PL_FREENUM1".equals(propertyId) || "PL_FREENUM2".equals(propertyId)) {
					if (field instanceof TextField) {
						((TextField) field).addValidator(new IntegerValidator("请输入数字"));
					}
				} else if ("PL_ID".equals(propertyId)) {
					if (field instanceof TextField) {
						((TextField) field).setRequired(true);
						((TextField) field).setRequiredError("必填项");
					}
				}
				if ("PL_FREETEXT1".equals(propertyId) && field instanceof TextField) {
					((TextField) field).setDescription("模板可用的占位符有:${省},${市},${区},${手机号码},${姓名},${性别},${年龄},${自由输入字段},${出生年},${出生月},${出生日},${来源},${产品名称},${电子邮件}");
				}

				return field;
			}
		});

		types.setNewItemsAllowed(true);
		// types.setNullSelectionAllowed(false);
		for (String s : PlanContainer.PLAN_TYPE_LIST) {
			types.addItem(s);
		}
	}

	private void setIcons() {
		delete.setIcon(new ThemeResource("icons/delete.png"));
		edit.setIcon(new ThemeResource("icons/edit.png"));
		save.setIcon(new ThemeResource("icons/accept.png"));
		cancel.setIcon(new ThemeResource("icons/back.png"));
		setIcon(new ThemeResource("icons/comment_edit.png"));
	}

	public void buttonClick(ClickEvent event) {
		Button source = event.getButton();

		if (source == save) {
			/* If the given input is not valid there is no point in continuing */
			if (!isValid()) {
				return;
			}
			logger.debug("ready to Save");
			commit();
			if (!newContactMode) {
				BeanItem item = (BeanItem) this.getItemDataSource();
				VOPlan config = (VOPlan) item.getBean();
				view.getPlanDAO().updateByPrimaryKey(config);
				getApplication().getMainWindow().showNotification("修改成功");
				view.load();
			} else if (newContactMode) {
				Item addedItem = view.PlanContainer.addItem(newVOPlan);

				BeanItem item = (BeanItem) this.getItemDataSource();
				VOPlan config = (VOPlan) item.getBean();
				view.getPlanDAO().insertSelective(config);
				getApplication().getMainWindow().showNotification("添加成功");
				view.load();

				newContactMode = false;
			}
			setReadOnly(true);
		} else if (source == cancel) {
			if (newContactMode) {
				newContactMode = false;
				/* Clear the form and make it invisible */
				setItemDataSource(null);
			} else {
				discard();
			}
			setReadOnly(true);
		} else if (source == delete) {
			ConfirmDialog.confirmYesNo(getApplication(), "确定吗?", new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					BeanItem item = (BeanItem) PlanForm.this.getItemDataSource();
					if (item == null) {
						getApplication().getMainWindow().showNotification("找不到数据");
						return;
					}
					VOPlan config = (VOPlan) item.getBean();
					view.getPlanDAO().deleteByPrimaryKey(config.getPL_ID());
					setItemDataSource(null);
					view.load();
				}
			});

		} else if (source == edit) {
			setReadOnly(false);
		}
	}

	@Override
	public void setItemDataSource(Item newDataSource) {
		newContactMode = false;

		if (newDataSource != null) {
			super.setItemDataSource(newDataSource);
			List<Object> orderedProperties = Arrays.asList(PlanContainer.NATURAL_COL_ORDER_FORM);
			super.setItemDataSource(newDataSource, orderedProperties);
			setReadOnly(true);
			getFooter().setVisible(true);
		} else {
			super.setItemDataSource(null);
			getFooter().setVisible(false);
		}
	}

	@Override
	public void setReadOnly(boolean readOnly) {
		super.setReadOnly(readOnly);
		if (!newContactMode && getItemDataSource() != null) {
			setReadOnlyByFieldName("PL_ID");
		}
		save.setVisible(!readOnly);
		cancel.setVisible(!readOnly);
		edit.setVisible(readOnly);
		delete.setVisible(readOnly);
	}

	private void setReadOnlyByFieldName(String string) {
		Field f = getField(string);
		if (f != null) {
			f.setReadOnly(true);
		} else {
			logger.warn("field is null:" + string);
		}

	}

	public void addObject() {
		// Create a temporary item for the form
		newVOPlan = new VOPlan();
		setItemDataSource(new BeanItem<VOPlan>(newVOPlan));
		newContactMode = true;
		setReadOnly(false);
	}
}
